package com.lucenten.collect.gnss.handler.files;

import cn.quevo.common.lang.NumberUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 硬件延迟
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2019/5/17 13:38
 * @Copyright 湘豫（北京）科技有限公司版权所有.All Rights Reserved.
 */
@Slf4j
public class HardwareDelay {
    /**
     * 读取硬件延迟信息
     *
     * @param root
     * @param currDate
     * @return
     * @author July july_sky@foxmail.com
     * @date 2019/5/17 14:15
     */
    public static Map<String, double[]> getBias(String root, LocalDateTime currDate) {
        Path biasFile = null;
        if (Files.notExists(Paths.get(root,currDate.getYear() + ""))) {
            return new HashMap<>();
        }
        try (Stream<Path> files = Files.list(Paths.get(root, currDate.getYear() + "")).sorted(Comparator.reverseOrder()).limit(1);) {
            biasFile = files.collect(Collectors.toList()).get(0);
        } catch (IOException e) {
            log.error("硬件延迟信息不存在",e);
        }
        if (biasFile == null) {
            return new HashMap<>();
        }

        Map<String, double[]> mapValue = new LinkedHashMap<>();
        try (Stream<String> lines = Files.lines(biasFile).filter(line -> !line.contains("%"));) {
            lines.forEach(line -> {
                String stationName = line.substring(0, 4).trim();
                double[] vals = new double[82];
                for (int i = 0; i < 82; i++) {
                    vals[i] = NumberUtils.toDouble(line.substring(4 + 10 * i, 4 + 10 * (i + 1)).trim());
                }
                mapValue.put(stationName, vals);
            });
        } catch (IOException e) {
            log.error("硬件延迟数据读取失败",e);
        }
        return mapValue;
    }
}
